<!DOCTYPE html>
<html>
<head>
    <!--    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">-->
    <title>Chat</title>
    <script src="/marked.min.js"></script>
    <script src="/echarts.min.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f5f5f5;
            margin: 0;
            padding: 0;
            display: flex;
            flex-direction: column;
            height: 100vh;
        }

        #chatbox {
            flex-grow: 1;
            border: 1px solid #ccc;
            overflow-y: auto;
            margin: 20px;
            padding: 10px;
            background-color: #fff;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
            }
            to {
                opacity: 1;
            }
        }

        .message {
            margin-bottom: 10px;
            border-radius: 5px;
            padding: 5px;
            line-height: 1.5;
            display: flex;
            flex-direction: column;
            animation: fadeIn 0.5s ease-in-out;
        }

        .message.user {
            align-items: flex-end;
        }

        .message.ai {
            align-items: flex-start;
        }

        .bubble {
            background-color: #d9edf7;
            border-radius: 10px;
            padding: 10px;
            position: relative;
            max-width: 70%;
            display: inline-block;
        }

        .message-header {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .name.ai {
            margin: 0;
        }

        .feedback-icons {
            display: flex;
            gap: 5px;
        }

        .feedback-icon {
            cursor: pointer;
        }

        .feedback-icon.useful {
            color: green;
        }

        .feedback-icon.not-useful {
            color: red;
        }

        .feedback-input {
            display: none;
            margin-top: 5px;
        }

        .selected {
            color: #4CAF50;
        }

        .disabled {
            color: #ccc;
            pointer-events: none;
        }

        .time.ai {
            margin-left: auto;
        }

        .bubble.ai {
            background-color: #d9edf7;
            border-radius: 10px;
            padding: 10px;
            position: relative;
            max-width: 70%;
            display: inline-block;
        }

        .params.ai {
            display: flex;
            flex-wrap: wrap;
            gap: 5px;
            margin-top: 10px;
        }

        .param-tag {
            background-color: #e1f5fe;
            border-radius: 3px;
            padding: 3px 6px;
            font-size: 0.8em;
            color: #0277bd;
            white-space: nowrap;
        }

        #message {
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 5px;
            margin: 0 20px;
            flex-grow: 1;
        }

        #send {
            padding: 10px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            margin: 0 20px;
        }

        #send:hover {
            background-color: #45a049;
        }

        #input-area {
            display: flex;
            margin-bottom: 20px;
        }

        table {
            border-collapse: collapse;
            width: 60%;
        }

        th, td {
            border: 1px solid black;
            padding: 8px;
            text-align: left;
        }

        th {
            background-color: #f2f2f2;
            font-weight: bold;
        }
    </style>
</head>
<body>
<div id="chatbox">
</div>
<div id="input-area">
    <input id="message" type="text" placeholder="Type your message here...">
    <button id="send">Send</button>
</div>

<script>

    var searchParams = new URLSearchParams(window.location.search);
    var isDebug = searchParams.get('isDebug')
    console.log('isDebug: ' + isDebug)

    // function debounce(func, wait) {
    //     let timeout;
    //     return function (...args) {
    //         clearTimeout(timeout);
    //         timeout = setTimeout(() => func.apply(this, args), wait);
    //     };
    // }

    var allImages = [];
    var sessionId = Date.now() + Math.random().toString(36).substr(2, 9);
    sessionStorage.setItem('sessionId', sessionId);

    var eventSource;  // 全局变量存储 EventSource 实例
    var aiMessageDiv; // 全局变量存储 AI 消息的 div
    var currentContent = ""; // 全局变量存储当前内容
    var lastJsonId = null; // 全局变量存储上一次的 jsonData.id

    // send 发送
    // const debouncedSendMessage = debounce(sendMessage, 300);
    document.getElementById("send").addEventListener("click", function () {
        sendMessage();
    });

    // shift + enter 发送
    document.getElementById("message").addEventListener("keydown", function (e) {
        if (e.key === 'Enter' && e.shiftKey) {
            e.preventDefault();
            sendMessage();
        }
    });

    // 消息发送
    function sendMessage() {
        var msg = document.getElementById("message").value;
        var msgDiv = document.createElement("div");
        var nameDiv = document.createElement("div");
        var bubbleDiv = document.createElement("div");
        msgDiv.className = "message user";
        nameDiv.textContent = "YOU";
        nameDiv.className = "name user";
        bubbleDiv.textContent = msg;
        bubbleDiv.className = "bubble user";
        msgDiv.appendChild(nameDiv);
        msgDiv.appendChild(bubbleDiv);
        document.getElementById("chatbox").appendChild(msgDiv);
        scrollToBottom();
        let apiUrl = '/api/chat/v1/init';
        fetch(apiUrl, {
            method: 'POST',
            headers: {
                'Accept': 'text/event-stream',
                'Content-Type': 'application/json',
                'appId': '10000',
                'timestamp': '1709538875',
                'token': '0dd9697a6b8e2d6d7d0634da9c0696c6'
            },
            body: JSON.stringify({
                conversationId: sessionStorage.getItem("sessionId"),
                version: "1.0.0",
                input: msg
            })
        })
            .then(response => {
                if (response.ok) {
                    return response.text();
                } else {
                    throw new Error('Network response was not ok');
                }
            })
            .then(data => {
                if (window.EventSource && data) {
                    var allData = JSON.parse(data);
                    // 关闭现有的 SSE 连接（如果有）
                    if (eventSource) {
                        eventSource.close();
                    }
                    createEventSource(allData.uid);
                } else {
                    alert("你的浏览器不支持SSE");
                }
            })
            .catch(error => {
                console.error('There has been a problem with your fetch operation:', error);
            });
        document.getElementById("message").value = "";
    }

    // 创建EventSource
    function createEventSource(uid) {
        eventSource = new EventSource('/api/chat/v1/sseMessage?uid=' + uid + '&conversationId=' + sessionStorage.getItem("sessionId") + '&appId=10000' + '&isDebug=' + isDebug);
        eventSource.onopen = function (event) {
            console.log('SSE链接成功');
        };
        eventSource.onmessage = function (event) {
            if (event.data) {
                sendChartData(event.data);
            }
            var jsonData = JSON.parse(event.data.replace("data:", ""));
            var eventContent = JSON.parse(jsonData.content);
            if (eventContent.data === "done") {
                eventSource.close();
            }
        };
        eventSource.onerror = function (error) {
            // console.log('SSE链接失败，重新发起连接');
            // eventSource.close();
            // setTimeout(function () {
            //     createEventSource(uid);
            // }, 3000); // 3秒后重新发起连接
        };
    }

    // 数据处理
    function sendChartData(data) {
        var jsonData = JSON.parse(data.replace("data:", ""));
        // 检查 jsonData.id 是否变化
        if (jsonData.id !== lastJsonId) {
            // 更新 lastJsonId
            lastJsonId = jsonData.id;
            // 重置 aiMessageDiv 和 currentContent
            aiMessageDiv = null;
            currentContent = "";
            allImages = []
        }

        // 如果 aiMessageDiv 未定义，则创建新的消息 div
        if (!aiMessageDiv) {
            aiMessageDiv = document.createElement("div");
            aiMessageDiv.className = "message ai";
            var headerDiv = document.createElement("div");
            var nameDiv = document.createElement("div");
            var timeDiv = document.createElement("div");
            var bubbleDiv = document.createElement("div");
            var paramsDiv = document.createElement("div");
            headerDiv.className = "message-header";
            nameDiv.textContent = "AI";
            nameDiv.className = "name ai";
            headerDiv.appendChild(nameDiv);
            var feedbackInput = document.createElement("input");
            feedbackInput.type = "text";
            feedbackInput.id = "feedback-text-" + jsonData.id;
            feedbackInput.placeholder = "Please provide feedback...";
            feedbackInput.className = "feedback-input";
            feedbackInput.onchange = function () {
                sendFeedbackWithText(jsonData.id);
            };
            var feedbackIconsDiv = document.createElement("div");
            feedbackIconsDiv.className = "feedback-icons";
            var usefulIcon = document.createElement("i");
            usefulIcon.id = "useful-" + jsonData.id;
            usefulIcon.className = "material-icons feedback-icon";
            usefulIcon.addEventListener("click", function () {
                handleUsefulClick(jsonData.id);
            });
            var notUsefulIcon = document.createElement("i");
            notUsefulIcon.id = "not-useful-" + jsonData.id;
            notUsefulIcon.className = "material-icons feedback-icon";
            notUsefulIcon.addEventListener("click", function () {
                handleNotUsefulClick(jsonData.id);
            });

            feedbackIconsDiv.appendChild(usefulIcon);
            feedbackIconsDiv.appendChild(notUsefulIcon);

            headerDiv.appendChild(feedbackIconsDiv);
            headerDiv.appendChild(feedbackInput);

            var date = new Date(jsonData.createTime);
            timeDiv.textContent = date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
            timeDiv.className = "time ai";
            headerDiv.appendChild(timeDiv);
            aiMessageDiv.appendChild(headerDiv);
            bubbleDiv.className = "bubble ai";
            aiMessageDiv.appendChild(bubbleDiv);
            aiMessageDiv.appendChild(paramsDiv);
            document.getElementById("chatbox").appendChild(aiMessageDiv);
            scrollToBottom();
        }
        var contentType = jsonData.contentType;
        var jsonContent = JSON.parse(jsonData.content);
        console.log(jsonContent);
        var jsonContentData = jsonContent.data;
        if (contentType === "TEXT") {
            var jsonPart = jsonContent.part;
            if (jsonPart === 0) {
                tipsFormatterContent(jsonContentData, aiMessageDiv.querySelector('.bubble'));
            }
            if (jsonPart === 1) {
                console.log(currentContent)
                currentContent += jsonContentData;
                appendFormattedContent(currentContent, aiMessageDiv.querySelector('.bubble'));
            }
            if (jsonPart === 2) {
                var jsonContentPartData = JSON.parse(jsonContentData);
                var listContent = formatListContent(jsonContentPartData);
                currentContent += listContent;
                appendFormattedContent(currentContent, aiMessageDiv.querySelector('.bubble'));
            }

        } else if (contentType === "CHART") {
            var jsonContentChartData = JSON.parse(jsonContentData);
            var answer = jsonContentChartData.answer;
            if (answer !== "") {
                appendFormattedContent(answer, aiMessageDiv.querySelector('.bubble'));
            }
            var imageUrls = jsonContentChartData.data;
            imageUrls.forEach(function (url) {
                allImages.push(url);
            });
        }
        allImages.forEach(function (imageUrl) {
            var imgElement = document.createElement("img");
            imgElement.src = imageUrl;
            imgElement.style.maxWidth = "100%";
            imgElement.style.height = "auto";
            imgElement.onerror = function () {
                console.error("Failed to load image: " + imageUrl);
            };
            imgElement.onload = function () {
                console.log("Image loaded successfully: " + imageUrl);
            };
            aiMessageDiv.querySelector('.bubble').appendChild(imgElement);
            var brElement = document.createElement("br");
            aiMessageDiv.querySelector('.bubble').appendChild(brElement);
        })
        scrollToBottom();
    }

    function appendFormattedContent(text, element) {
        element.innerHTML = marked.parse(text);
    }

    function tipsFormatterContent(text, tipsDiv) {
        tipsDiv.innerHTML = "";
        var tipDiv = document.createElement("div");
        tipDiv.style.padding = "5px";
        tipDiv.style.borderRadius = "5px";
        tipDiv.style.marginBottom = "10px";
        tipDiv.style.fontWeight = "bold";
        tipDiv.textContent = text;
        tipsDiv.appendChild(tipDiv);
    }

    function formatListContent(dataList) {
        var listHtml = '<div style="font-size: 18px; font-weight: bold;">引用文档:</div>';
        listHtml += '<ul>';
        dataList.forEach(function (item) {
            var formattedTitle = item.title.replace(/\n{2,}/g, '\n');
            listHtml += '<li style="font-size: 14px;">';
            listHtml += formattedTitle + ' <a href="' + item.source + '" target="_blank" style="font-size: 14px;">查看</a>';
            listHtml += '</li>';
        });
        listHtml += '</ul>';
        return listHtml;
    }

    function scrollToBottom() {
        chatbox.scrollTop = chatbox.scrollHeight;
    }

    function handleUsefulClick(id) {
        sendFeedback(id, 1, '');
        document.getElementById('useful-' + id).classList.add('selected');
        document.getElementById('not-useful-' + id).classList.add('disabled');
    }

    function handleNotUsefulClick(id) {
        var feedbackInput = document.getElementById('feedback-text-' + id);
        feedbackInput.style.display = 'block';
        feedbackInput.focus();

        document.getElementById('useful-' + id).classList.add('disabled');
        document.getElementById('not-useful-' + id).classList.add('selected');
    }

    function sendFeedbackWithText(id) {
        var feedbackText = document.getElementById('feedback-text-' + id).value;
        sendFeedback(id, 2, feedbackText);
        document.getElementById('feedback-text-' + id).style.display = 'none';
    }

    function sendFeedback(id, usefulness, feedback) {
        fetch(window.location + 'api/chat/record/feedback', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'appId': '10000',
                'timestamp': '1709538875',
                'token': '0dd9697a6b8e2d6d7d0634da9c0696c6'
            },
            body: JSON.stringify({
                id: id,
                usefulness: usefulness,
                feedback: feedback
            })
        })
            .then(response => response.json())
            .then(data => {
                console.log('Feedback sent:', data);
            })
            .catch(error => {
                console.error('Error sending feedback:', error);
            });
    }
</script>
</body>
</html>
